﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HarmonyLib;
using UnityEngine;
internal class ET_ModuleLogic
{
    private static XUiV_Button btnToQuestPOI;
    public static float minDistanceTeleTo;
    public static float waitToHandleAction;
    public static bool isAvailableInBM;
    public static bool globalBroadcastEnable;
    public static string key_ChatCmdBackPos;
    public static Vector3 LastPretelePos
    {
        get;
        set;
    }
    [HarmonyPatch(typeof(XUiC_QuestListWindow), nameof(XUiC_QuestListWindow.Init))]
    public class XUiC_QuestListWindow_Patch
    {
        [HarmonyTranspiler]
        [HarmonyPostfix]
        public static void AddNewControl_Fix(XUiC_QuestListWindow __instance, ref XUiC_QuestList ___questList)
        {
            btnToQuestPOI = (XUiV_Button)__instance.GetChildById("btn_TeleToQuest").ViewComponent;
            if (btnToQuestPOI != null)
            {
                XUiC_QuestList questListEntry = ___questList;
                btnToQuestPOI.Controller.OnPress += async delegate
                {
                    EntityPlayerLocal e = __instance.xui.playerUI.entityPlayer;
                    if (IsAvailable(e.PlayerUI, questListEntry.SelectedEntry))
                    {
                        await Prepare(e);
                        GameManager.Instance.StartCoroutine(HandleAction(e, waitToHandleAction, () =>
                        {
                            e.SetPosition(questListEntry.SelectedEntry.Quest.Position);
                            e.Respawn(RespawnType.Teleport);
                        }, () =>
                        {
                            OnPlayerTeleported(e, questListEntry.SelectedEntry.Quest);
                        }));
                    }
                };
            }
        }
    }
    [HarmonyPatch(typeof(NetPackageChat), nameof(NetPackageChat.Setup))]
    public class NetPackageChat_Setup_Patch
    {
        [HarmonyPrefix]
        public static bool PrependCommandCheck(ref EChatType _chatType, ref int _senderEntityId, ref string _msg, ref string _mainName, ref bool _localizeMain, ref List<int> _recipientEntityIds)
        {
            Entity requesterEntity = GameManager.Instance.World.GetEntity(_senderEntityId);
            if (requesterEntity != null)
            {
                if (_msg.Equals(key_ChatCmdBackPos, StringComparison.OrdinalIgnoreCase))
                {
                    if (LastPretelePos != null && LastPretelePos != default)
                    {
                        (requesterEntity as EntityPlayer).SetPosition(LastPretelePos);
                        (requesterEntity as EntityPlayer).Respawn(RespawnType.Teleport);
                        (requesterEntity as EntityPlayer).emodel.avatarController.PlayPlayerFPRevive();
                        GameManager.ShowTooltip((requesterEntity as EntityPlayerLocal), "[i]你已返回上一次出发点[/i]");
                    }
                    else
                    {
                        GameManager.ShowTooltip((requesterEntity as EntityPlayerLocal), "[FF0000][i]当前无法返回至出发点！[/i]");
                    }
                }
            }
            return true;
        }
    }
    [HarmonyPatch(typeof(GameManager), nameof(GameManager.Disconnect))]
    public class GameManager_Disconnect_Patch
    {
        [HarmonyPostfix]
        public static void ClearCVar()
        {
            minDistanceTeleTo = default;
            waitToHandleAction = default;
            isAvailableInBM = default;
            globalBroadcastEnable = default;
            LastPretelePos = default;
            Debug.Log("<b>[ETModule] 清除变量及对象完成.</b>");
        }
    }
    private class TooltipInterface : MonoBehaviour
    {
        private float cd_TooltipNum;
        private GUIStyle fontStyle = new GUIStyle();
        void Start()
        {
            fontStyle.fontSize = 45;
            fontStyle.fontStyle = FontStyle.Bold;
            fontStyle.normal.textColor = Color.white;
            fontStyle.clipping = TextClipping.Clip;
            fontStyle.alignment = TextAnchor.MiddleCenter;
            cd_TooltipNum = waitToHandleAction;
            InvokeRepeating("OnTooltipTimerChange", 1, 1);
        }
        void OnTooltipTimerChange()
        {
            if (cd_TooltipNum > 0)
            {
                cd_TooltipNum -= 1;
            }
        }
        void OnGUI()
        {
            GUI.Label(new Rect((Screen.width - 800) / 2, (Screen.height - 200) / 2, 800, 200), $"传送倒计时：{cd_TooltipNum.ToString()}", fontStyle);
        }
    }
    private static bool IsAvailable(LocalPlayerUI @playerUi, XUiC_QuestEntry @selected)
    {
        if (!isAvailableInBM && SkyManager.IsBloodMoonVisible())
        {
            GameManager.ShowTooltip(@playerUi.entityPlayer, "已禁止在血月期间使用该功能");
            return false;
        }
        if (@selected == null || !@selected.Quest.Tracked)
        {
            GameManager.ShowTooltip(@playerUi.entityPlayer, "你必须先选择一个并切换此任务应用才可以使用POI任务点的传送功能");
            return false;
        }
        string questLocalizationId = Localization.Get(@selected.Quest.ID, GamePrefs.GetString(EnumGamePrefs.Language));
        if (!@selected.Quest.HasPosition)
        {
            GameManager.ShowTooltip(@playerUi.entityPlayer, $"{questLocalizationId} 不具有POI任务点，无法使用传送");
            return false;
        }
        if (Convert.ToInt32(Vector3.Distance(@selected.Quest.Position, @playerUi.entityPlayer.position)) < minDistanceTeleTo)
        {
            GameManager.ShowTooltip(@playerUi.entityPlayer, $"已经在 {questLocalizationId} 附近");
            return false;
        }
        return true;
    }
    private static IEnumerator HandleAction(EntityPlayerLocal localPlayer, float waitForTele, Action callBack_TEPlayer, Action callBack_Teleported)
    {
        LastPretelePos = localPlayer.position;
        yield return new WaitForSeconds(waitForTele);
        callBack_TEPlayer?.Invoke();
        callBack_Teleported?.Invoke();
    }
    private static async Task Prepare(EntityPlayerLocal @localPlayer)
    {
        try
        {
            @localPlayer.PlayerUI.transform.gameObject.SetActive(false);
            if (@localPlayer.transform.GetComponent<TooltipInterface>() == null)
            {
                @localPlayer.transform.gameObject.AddComponent<TooltipInterface>();
            }
            return;
        }
        catch (Exception ex)
        {
            Debug.LogWarning(ex.ToString());
        }
    }
    private static void OnPlayerTeleported(EntityPlayerLocal @localPlayer, Quest @quest)
    {
        try
        {
            @localPlayer.emodel.avatarController.PlayPlayerFPRevive();
            if (@localPlayer.transform.GetComponent<TooltipInterface>() != null)
            {
                GameObject.Destroy(@localPlayer.transform.GetComponent<TooltipInterface>());
            }
            GameManager.ShowTooltip(@localPlayer, $"你已到达 {Localization.Get(@quest.ID, GamePrefs.GetString(EnumGamePrefs.Language))} 的POI任务点");
            if (globalBroadcastEnable)
            {
                GameManager.Instance.ChatMessageServer(null, EChatType.Global, @localPlayer.entityId, string.Concat(new string[]
                {
                    "玩家",
                     "\"" + @localPlayer.EntityName + "\"",
                    "于",
                    DateTime.Now.ToString(),
                    "使用了POI任务点传送功能",
                    $"(所属任务：{Localization.Get(@quest.ID, GamePrefs.GetString(EnumGamePrefs.Language))})"
                }), "Server", false, null);
            }
            @localPlayer.PlayerUI.transform.gameObject.SetActive(true);
        }
        catch (Exception ex)
        {
            Debug.LogWarning(ex.ToString());
        }
    }
}
